package com.starxg.m3u8.gui;

import javafx.scene.AccessibleAttribute;
import javafx.scene.Cursor;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.util.Callback;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import com.starxg.m3u8.controller.InitializationControl;
import com.starxg.m3u8.controller.InitializationWindow;
import com.starxg.m3u8.controller.MainController;
import com.starxg.m3u8.parser.M3U8Item;
import com.starxg.m3u8.parser.M3U8ItemStatus;

/**
 * M3U8TableView
 *
 * @author huangxingguang@lvmama.com
 * @date 2020-08-13 23:05
 */
@Slf4j
public class M3U8TableView extends TableView<M3U8Item> implements InitializationControl<MainController>, InitializationWindow {
    private MainController controller;

    @Override
    public void init(MainController controller) {
        this.controller = controller;
        initView();
        initData();
        initEvent();
    }

    @Override
    public void initView() {
        getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

        M3U8TableColumn<M3U8Item, Object> tcNum = new M3U8TableNumberColumn<>("序号");
        tcNum.prefWidthProperty().bind(widthProperty().multiply(.1));
        tcNum.getStyleClass().add("text-center");
        M3U8TableColumn<M3U8Item, Object> tcFilename = new M3U8TableColumn<>("文件名");
        tcFilename.prefWidthProperty().bind(widthProperty().multiply(.15));
        tcFilename.setCellValueFactory(new PropertyValueFactory<>("name"));
        M3U8TableColumn<M3U8Item, Object> tcUrl = new M3U8TableColumn<>("地址");
        tcUrl.prefWidthProperty().bind(widthProperty().multiply(.53));
        tcUrl.setCellValueFactory(new PropertyValueFactory<>("url"));

        M3U8TableColumn<M3U8Item, Double> tcProgress = new M3U8TableColumn<>("进度");
        tcProgress.prefWidthProperty().bind(widthProperty().multiply(.1));
        tcProgress.setCellValueFactory(new PropertyValueFactory<>("progress"));
        tcProgress.getStyleClass().add("text-center");
        tcProgress.setCellFactory(new Callback<>() {
            @Override
            public TableCell<M3U8Item, Double> call(TableColumn<M3U8Item, Double> param) {
                return new TableCell<>() {
                    @Override
                    protected void updateItem(Double progress, boolean empty) {
                        super.updateItem(progress, empty);
                        this.setGraphic(null);
                        setText(null);
                        if (!empty) {
                            if (progress == 0) {
                                setText("-");
                            } else if (progress == 100 || getItems().get(getIndex()).getStatus() == M3U8ItemStatus.SUCCEEDED) {
                                setText("100%");
                            } else {
                                setText(String.format("%.2f%%", progress));
                            }
                        }
                    }
                };
            }
        });

        M3U8TableColumn<M3U8Item, M3U8ItemStatus> tcStatus = new M3U8TableColumn<>("状态");
        tcStatus.prefWidthProperty().bind(widthProperty().multiply(.12));
        tcStatus.setCellValueFactory(new PropertyValueFactory<>("status"));
        tcStatus.getStyleClass().add("text-center");
        tcStatus.setCellFactory(new Callback<>() {
            @Override
            public TableCell<M3U8Item, M3U8ItemStatus> call(TableColumn<M3U8Item, M3U8ItemStatus> param) {
                return new TableCell<>() {
                    @Override
                    protected void updateItem(M3U8ItemStatus status, boolean empty) {
                        super.updateItem(status, empty);
                        setGraphic(null);
                        if (!empty) {
                            Text text = new Text(status.getMsg());

                            switch (status) {
                                case WAITING:
                                    break;
                                case RUNNING:
                                    text.setFill(Color.rgb(0, 117, 218));
                                    break;
                                case SUCCEEDED:
                                    text.setFill(Color.GREEN);
                                    break;
                                case FAILED:
                                    text.setFill(Color.RED);
                                    text.setUnderline(true);
                                    text.setOnMouseClicked(e -> {
                                        M3U8Item item = getItems().get(getIndex());
                                        Alert alert = new Alert(Alert.AlertType.ERROR);
                                        alert.setTitle("下载失败");
                                        alert.setHeaderText(null);
                                        alert.initOwner(controller.getStage());
                                        alert.setContentText(item.getError().getMessage());
                                        String stackTrace = ExceptionUtils.getStackTrace(item.getError());
                                        TextArea textArea = new TextArea(stackTrace);
                                        textArea.setEditable(false);
                                        textArea.setWrapText(true);
                                        textArea.setMaxWidth(Double.MAX_VALUE);
                                        textArea.setMaxHeight(Double.MAX_VALUE);
                                        alert.getDialogPane().setExpandableContent(textArea);
                                        alert.getDialogPane().setExpanded(true);
                                        alert.showAndWait();
                                    });
                                    text.setCursor(Cursor.HAND);

                                    break;
                                case PAUSED:
                                    text.setFill(Color.ORANGERED);
                                    break;
                                case RETRYING:
                                    text.setFill(Color.BROWN);
                                    break;
                            }

                            this.setGraphic(text);
                        }
                    }

                };
            }
        });

        getColumns().add(tcNum);
        getColumns().add(tcFilename);
        getColumns().add(tcUrl);
        getColumns().add(tcProgress);
        getColumns().add(tcStatus);
        setPlaceholder(new Text("空"));
    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {
        MenuItem copy = new MenuItem("复制地址");
        copy.setOnAction(e -> {
            M3U8Item item = getSelectionModel().getSelectedItem();
            if (item == null) {
                return;
            }

            ClipboardContent clipboardContent = new ClipboardContent();
            clipboardContent.putString(item.getUrl().toString());
            Clipboard.getSystemClipboard().setContent(clipboardContent);
        });
        setContextMenu(new ContextMenu(copy));
    }

    @Override
    protected void layoutChildren() {
        super.layoutChildren();
        ScrollBar scrollBar = (ScrollBar) queryAccessibleAttribute(AccessibleAttribute.HORIZONTAL_SCROLLBAR);
        if (scrollBar != null && scrollBar.isVisible()) {
            scrollBar.setPrefHeight(0);
            scrollBar.setMaxHeight(0);
            scrollBar.setOpacity(1);
            scrollBar.setVisible(false);
        }
    }

}
